package io.gitee.hefren.hhregistry.cluster;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Objects;

/**
 * @Date 2024/5/22
 * @Author lifei
 */
public class Selection {

    private static final Logger log = LoggerFactory.getLogger(Selection.class);

    /**
     * 选主
     */
    public void selectLeader(List<Server> serverList) {
        List<Server> leaderList = serverList.stream().filter(Server::getStatus).filter(Server::getLeader).toList();
        if (leaderList.isEmpty()) {
            log.debug("===> ****** select for no leader");
            select(serverList);
        } else if (leaderList.size() > 1) {
            log.debug("===> ++++ select for more one leader");
            select(serverList);
        }else {
            log.debug("===> already have a leader!");
        }
    }

    private void select(List<Server> serverList) {
        Server candidate = null;
        for (Server server : serverList) {
            server.setLeader(false);
            if (server.getStatus()) {
                if (Objects.isNull(candidate)) {
                    candidate = server;
                } else if (candidate.hashCode() > server.hashCode()) {
                    candidate = server;
                }
            }
        }
        if (Objects.nonNull(candidate)) {
            candidate.setLeader(true);
        }
    }
}
